import { axios } from "@/tools/request"

export default {
	state: {
		message: {
			chapterList: [],
		},
		coursewares: {},
	},
	mutations: {
		setMessage(state, data) {
			state.message = data
		},
		setCourseware(state, data) {
			state.coursewares = data
		},
		getCoureswareIndex(state, id) {
			const { coursewaresList } = this.getters
			state.index = coursewaresList.findIndex(item => item.id === id)
		},
	},
	actions: {
		async getCourseInfo({ commit }, id) {
			const data = await axios.get("/api/study/course/studyCourse/info", {
				id,
			})
			commit("setMessage", data)
			return data
		},
		async getCourseware({ commit }, query) {
			try {
				const data = await axios.post("/api/study/course/studyCourseLog/info", {
					courseId: query.courseId,
					chapterId: query.chapterId,
					coursewareId: query.coursewareId,
				})
				data.urls = []

				if (data.coursewareType === 1 || data.coursewareType === 3) {
					const urls = JSON.parse(data.coursewareUrl)
					if (Array.isArray(urls)) {
						data.urls = urls.map(item => item.url)
					}
				}

				commit("setCourseware", data)
				return data
			} catch (error) {
				console.log(error)
			}
		},
	},
	getters: {
		coursewareLength(state) {
			return state.message.chapterList.reduce((total, item) => {
				return total + (item.coursewares ? item.coursewares.length : 0)
			}, 0)
		},
		coursewaresList(state) {
			return state.message.chapterList.reduce((total, item) => {
				item.coursewares = item.coursewares
					? item.coursewares.map(courseware => {
							return {
								...courseware,
								chapterId: item.id,
							}
					  })
					: []

				return total.concat(item.coursewares)
			}, [])
		},
		coursewaresIndex(state, getters) {
			return getters.coursewaresList.findIndex(
				item => item.id === state.coursewares.id && item.chapterId === state.coursewares.chapterId
			)
		},
		prevCoursewaresId(_state, getters) {
			return getters.coursewaresList[getters.coursewaresIndex - 1]?.id
		},
		prevChapterId(_state, getters) {
			return getters.coursewaresList[getters.coursewaresIndex - 1]?.chapterId
		},
		nextCoursewaresId(_state, getters) {
			return getters.coursewaresList[getters.coursewaresIndex + 1]?.id
		},
		nextChapterId(_state, getters) {
			return getters.coursewaresList[getters.coursewaresIndex + 1]?.chapterId
		},
	},
}
